<template>
  <div style="height: 100vh;background: url('/img/loginBG.png') no-repeat;background-size: cover"
       class="container-fluid d-flex justify-content-center align-items-center">
    <div class="row">
      <div class="col">
        <div class="card" style="width: 21rem;background-color:rgba(0,0,0,0.5);">
          <template v-if="isLogin">
            <form ref="loginForm" class="needs-validation" novalidate>
              <div class="card-body">
                <div class="form-floating mb-3">
                  <input type="text" v-model.trim="SignForm.account" class="form-control" @focusout="handleChange"
                         id="account" placeholder="账号" required>
                  <label for="account">账号</label>
                  <div id="accountTip" class="invalid-feedback">
                    {{ Tip }}
                  </div>
                </div>
                <div class="form-floating">
                  <input type="password" v-model="SignForm.pwd" class="form-control" id="pwd" @focusout="handleChange"
                         placeholder="密码" required>
                  <label for="pwd">密码</label>
                  <div id="pwdTip" class="invalid-feedback">
                    {{ Tip }}
                  </div>
                </div>
                <div class="form-check form-switch mt-2">
                  <input class="form-check-input" v-model="SignForm.isAdmini" type="checkbox" role="switch" id="admin">
                  <label class="form-check-label" for="admin">管理员登录</label>
                </div>
                <div class="col-auto d-flex mt-2">
                  <label for="yzm" class="visually-hidden">验证码</label>
                  <input type="text" style="width: 150px" class="form-control" id="yzm" @focusout="handleChange"
                         placeholder="验证码" required>
                  <span class="yzm" v-html="vcode"></span>
                  <div id="yzmTip" class="invalid-feedback">
                    {{ Tip }}
                  </div>
                </div>
                <div class="d-grid gap-2 mt-2">
                  <button class="btn btn-primary" type="button" @click="handleClickLogin">登录</button>
                  <button class="btn btn-primary" type="button" @click="isLogin=false">注册</button>
                </div>
              </div>
            </form>
          </template>
          <template v-else>
            <el-page-header @back="isLogin = true" content="注册页面"></el-page-header>
            <registerForm></registerForm>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>
<script>

import user from "../api/user";
import registerForm from "../components/registerForm";

export default {
  name: "Login",
  data() {
    return {
      vcode: '',
      isLogin: true,
      SignForm: {
        account: '',
        pwd: '',
        validateCode: '',
        isAdmini: false,
      },
      Tip: ''
    }

  },
  components: {
    registerForm
  },
  created() {
  },
  mounted() {
    if (!localStorage.getItem("vcode")) {
      user.getValidate().then(r => {
        this.vcode = r.data.data.code
        localStorage.setItem("vcode", r.data.data.code)
        localStorage.setItem("id", r.data.data.id)
      }).catch(err => {
        console.log(err)
      })
    } else {
      this.vcode = localStorage.getItem("vcode")
    }
    //过期删除验证码
    setTimeout(() => {
      localStorage.setItem("vcode", "")
      localStorage.setItem("id", "")
    }, 3 * 60 * 1000)
  },
  methods: {

    handleClickLogin() {
      if (this.$refs.loginForm.checkValidity()) {
        const param = {
          account: this.SignForm.account,
          isAdmini: this.SignForm.isAdmini
        }
        const loading = this.$loading({
          lock: true,
          text: '登陆中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        user.GetPublicKeyByAccount(param).then(r => {
          const {publicKey} = r.data.data
          // eslint-disable-next-line no-undef
          const Key = new NodeRSA({b: 512})
          Key.importKey(publicKey, "pkcs1-public")
          // 加密
          const pwd = Key.encrypt(this.SignForm.pwd)
          const param = {
            ...this.SignForm
          }
          param.pwd = pwd
          user.signUp(param).then(r => {
            if (r.data.status === "200" && r.data.data.msg === '') {
              localStorage.setItem("userName", r.data.data.userName)
              localStorage.setItem("userID", r.data.data.userID)
              this.$router.replace("/").catch(() => {
                this.$router.replace("/")
              })
            } else {
              this.$message.error(r.data.data.msg);
            }
            loading.close()
          })
        }).catch(err => {
          this.$message.error('登录失败！' + err);
          loading.close()
        })
      }
    },

    handleChange(el) {
      switch (el.target.id) {
        case 'account':
          if (el.target.value === '') {
            el.target.classList.add("is-invalid")
            this.Tip = "请输入账号"
          } else {
            el.target.classList.add("is-valid")
            el.target.classList.remove("is-invalid")
          }
          break;
        case 'pwd':
          if (el.target.value === '') {
            el.target.classList.add("is-invalid")
            this.Tip = "请输入密码"
          } else if (el.target.value.length < 8) {
            el.target.classList.add("is-invalid")
            this.Tip = "密码长度小于8"
          } else {
            el.target.classList.add("is-valid")
            el.target.classList.remove("is-invalid")
          }
          break;
        case 'yzm':
          if (el.target.value === '') {
            el.target.classList.add("is-invalid")
            this.Tip = "请输入验证码"
          } else if (el.target.value.length !== 4) {
            el.target.classList.add("is-invalid")
            this.Tip = "请输入4位验证码"
          } else {
            const param = {
              valiadate: el.target.value.toLowerCase(),
              id: localStorage.getItem("id")
            }
            user.Compare(param).then(r => {
              if (r.data.data.result) {
                el.target.classList.add("is-valid")
                el.target.classList.remove("is-invalid")
              } else {
                el.target.classList.add("is-invalid")
                this.Tip = "验证码错误"
              }
            })

          }
          break;
      }
    }
  }
}

</script>

<style scoped>
input, button {
  background-color: rgba(176, 168, 168, 0.1);
  color: white;
}

.yzm, label {
  color: #b4b4b4
}

.el-page-header {
  color: #86eedb;
  margin-top: 10px;
}

/deep/ .el-page-header__content {
  color: #86eedb;
}
</style>